<?php
namespace app\admin\controller;
use think\Db;
class Tixian extends Base {
// 定义配置项
    private $config=array(
        'APPID'              => 'wx79afdec9ad2e67a2', // 微信支付APPID.
        'MCHID'              => '1557327661', // 微信支付MCHID 商户收款账号
        'KEY'                => 'qAIpKcjJQrgQJMbzfNqYoBBgFj1STO31', // 微信支付KEY
        'APPSECRET'          => '81b17ac2628875727b2393c1bb285e05', // 公众帐号secert (公众号支付专用)
        'NOTIFY_URL'         => '', // 接收支付状态的连接

    );
    //----------------------------提现 S-----------------------------------
    /**
     * 获取提现数据
     */
    public function index(){
        if(request()->isAjax ()){
            extract(input());
            $map = [];
            if(isset($key)&&$key!="")
            {
                $map['ask_number|fen_realname|fen_phone'] = ['like',"%" . $key . "%"];
            }
            if(isset($level)&&$level!="")
            {
                $map['a.ask_status'] = $level;
            }

            $Nowpage = input('page') ? input('page'):1;
            $limits = input("limit")?input("limit"):10;// 获取总条数;
            $count = Db::table('up_ask_money')->alias('a')
                ->join('up_fenxiao f','a.ask_fen_id=f.fen_id','LEFT')
                ->where($map)
                ->count();
            $lists = Db::table('up_ask_money')->alias('a')
                ->join('up_fenxiao f','a.ask_fen_id=f.fen_id','LEFT')
                ->where($map)
                ->order('ask_status asc')
                ->page($Nowpage, $limits)
                ->field('a.*,fen_id,fen_realname,fen_phone')
                ->select();//计算总页面
            return json(['code'=>220,'msg'=>'','count'=>$count,'data'=>$lists]);
        }
        return $this->fetch("tixian/index");
    }

    /**
     * 审核通过
     * @return mixed|\think\response\Json
     */
    public function memberPass(){
        $ask_id = input('ask_id');
        if(request()->isPost()){
            $ask = Db::table('up_ask_money')->where('ask_id', $ask_id)->find();
            if($ask['ask_status'] != 1){
                return json(['code' => 100, 'msg' => '请勿重复操作！']);
            }
            $am_remark = input('am_remark');
            $data = [
                'ask_status' => 2,
                'ask_remark' => $am_remark,
                'ask_dotime' => date('Y-m-d H:i:s'),
            ];
            $have = $this->tiXianChaXun($ask['ask_number']);
            if($have['status'] == 200){
                Db::table('up_ask_money')->where('ask_id',$ask_id)
                    ->update(['ask_status'=>2]);
                return json_encode(['status'=>0,'msg'=>'已经有此笔退款']);
            }else{
                $res = $this->userTiXian($ask['ask_number'],$ask['ask_openid'],$ask['ask_money']);
                if($res['status'] == 200){
                    Db::table('up_ask_money')->where('ask_id', $ask_id)->update($data);
                    return json(['code' => 200, 'msg' => '审核成功']);
                }else{
                    return json(['code'=>0,'msg'=>$res['msg']]);
                }
            }
        }
        $this->assign('ask_id', $ask_id);
        return $this->fetch('tixian/memberpass');
    }

    /**
     * 审核驳回
     * @return mixed|\think\response\Json
     */
    public function memberRefuse(){
        $ask_id = input('ask_id');
        if(request()->isPost()){
            $sss = Db::table('up_ask_money')->where('ask_id', $ask_id)->field('ask_status,ask_fen_id,ask_money')->find();
            if($sss['ask_status'] != 1){
                return json(['code' => 100, 'msg' => '请勿重复操作！']);
            }
            $am_remark = input('am_remark');
            $data = [
                'ask_status' => 3,
                'ask_remark' => $am_remark,
                'ask_dotime' => date('Y-m-d H:i:s')
            ];
            Db::startTrans();
            try{
                Db::table('up_ask_money')->where('ask_id', $ask_id)->update($data);
                Db::table('up_fenxiao')->where('fen_id', $sss['ask_fen_id'])
                    ->setInc('fen_money',$sss['ask_money']);
                Db::commit();
                return json(['code' => 200, 'msg' => '审核成功']);
            }catch (\Exception $e) {
                Db::rollback();
                return json(['code' => 100, 'msg' => '审核失败，请刷新重试！']);
            }
        }
        $this->assign('ask_id', $ask_id);
        return $this->fetch('tixian/memberrefuse');
    }






    /**
     * 提现
     * 提现的这个如果是201也把状态改了
     * 查询的那个如果是200说明已经提现过了，拒绝的时候也要查询一下，200就把状态改了，防止数据出错
     */
    public function userTiXian($refundNo,$openid,$money){
        $url = "https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers";
        $data["mch_appid"] = $this->config['APPID'];//微信开放平台审核通过的应用APPID
        $data["mchid"] = $this->config['MCHID'];//商户号
        $data["nonce_str"] = $this->getRandChar(32);//随机字符串
        $data["partner_trade_no"] = $refundNo;
        $data["openid"] = $openid;
        $data["check_name"] = 'NO_CHECK';
        $data["amount"] = $money*100;
        $data["desc"] = '提现到账通知';
        $data["spbill_create_ip"] = $_SERVER['REMOTE_ADDR'];
        $sign = $this->makeSign($data);
        $data['sign'] = $sign;
        $xml = $this->toXml($data);
        $response = $this->postXmlCurl($xml, $url, '', true, '/appcert/apiclient_cert.pem', '/appcert/apiclient_key.pem');
        $responseArr = $this->toArray($response);
        if (!is_array($responseArr) || count($responseArr) <= 0) {
            $return['msg'] = '网络请求繁忙';
            $return['status'] = 0;
        } else if ($responseArr['return_code'] == 'FAIL') {
            $return['msg'] = $responseArr['return_msg'];
            $return['status'] = 0;
        } else {
            if ($responseArr['result_code'] == 'FAIL') {
                $return['msg'] = $responseArr['err_code_des'];
                $return['status'] = 0;
            } else {
                $return['text'] = $responseArr;
                $return['status'] = 200;
            }
        }
        return $return;
    }
    /**
     * 提现查询
     */
    public function tiXianChaXun($refundNo){
        $url = "https://api.mch.weixin.qq.com/mmpaymkttransfers/gettransferinfo";
        $data["appid"] = $this->config['APPID'];//微信开放平台审核通过的应用APPID
        $data["mch_id"] 	  = $this->config['MCHID'];//商户号
        $data["nonce_str"] 	  = $this->getRandChar(32);//随机字符串
        $data["partner_trade_no"]   = $refundNo;
        $sign=$this->makeSign($data);
        $data['sign']=$sign;
        $xml=$this->toXml($data);
        $response 	= $this->postXmlCurl($xml, $url,'',true,'/appcert/apiclient_cert.pem','/appcert/apiclient_key.pem');
        $responseArr=$this->toArray($response);
        if(!is_array($responseArr) || count($responseArr)<=0){
            $return['msg'] = '网络请求繁忙';
            $return['status'] = 0;
        }else if($responseArr['return_code'] == 'FAIL'){
            $return['msg'] = $responseArr['return_msg'];
            $return['status'] = 0;
        }else{
            if($responseArr['result_code'] == 'FAIL'){
                $return['msg'] = $responseArr['err_code_des'];
                $return['status'] = 0;
            }else{
                $return['text'] = $responseArr;
                $return['status'] = 200;
            }
        }
        return $return;
    }
    function postXmlCurl($xml, $url, $second=30, $useCert=false, $sslcert_path, $sslkey_path)
    {
        $ch = curl_init();
        //设置超时
        curl_setopt($ch, CURLOPT_TIMEOUT, $second);
        curl_setopt($ch,CURLOPT_URL, $url);

        //设置header
        curl_setopt($ch, CURLOPT_HEADER, FALSE);
        //要求结果为字符串且输出到屏幕上
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,FALSE);
        curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,FALSE);

        if($useCert == true){
            curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false);
            curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,false);
//            curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,TRUE);
//			curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,1);//严格校验
            //设置证书
            $path = $_SERVER['DOCUMENT_ROOT'];
            curl_setopt($ch,CURLOPT_SSLCERTTYPE,'PEM');
            curl_setopt($ch,CURLOPT_SSLCERT, $path.$sslcert_path);
            curl_setopt($ch,CURLOPT_SSLKEYTYPE,'PEM');
            curl_setopt($ch,CURLOPT_SSLKEY, $path.$sslkey_path);
//            curl_setopt($ch,CURLOPT_CAINFO, __DIR__.'/cert/rootca.pem');
        }
        //post提交方式
        curl_setopt($ch, CURLOPT_POST, TRUE);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
        //运行curl
        $data = curl_exec($ch);
        //返回结果
        if($data){
            curl_close($ch);
            return $data;
        } else {
            $error = curl_errno($ch);
            curl_close($ch);
            return false;
        }
    }
    //----------------------------提现 E-----------------------------------
    /**
     * 输出xml字符
     * @throws WxPayException
     **/
    public function toXml($data){
        //var_dump($data);
        if(!is_array($data) || count($data) <= 0){
            //throw new WxPayException("数组数据异常！");
        }
        $xml = "<xml>";
        foreach ($data as $key=>$val){
            if (is_numeric($val)){
                $xml.="<".$key.">".$val."</".$key.">";
            }else{
                $xml.="<".$key."><![CDATA[".$val."]]></".$key.">";
            }
        }
        $xml.="</xml>";
        return $xml;
    }

    /**
     * 生成签名
     * @return 签名，本函数不覆盖sign成员变量，如要设置签名需要调用SetSign方法赋值
     */
    public function makeSign($data){
        // 去空
        $data=array_filter($data);
        //签名步骤一：按字典序排序参数
        ksort($data);
        $string_a=http_build_query($data);
        $string_a=urldecode($string_a);
        //签名步骤二：在string后加入KEY
        $config=$this->config;
        $string_sign_temp=$string_a."&key=".$config['KEY'];
        //签名步骤三：MD5加密
        $sign = md5($string_sign_temp);
        // 签名步骤四：所有字符转为大写
        $result=strtoupper($sign);
        return $result;
    }

    /**
     * 将xml转为array
     * @param  string $xml xml字符串
     * @return array       转换得到的数组
     */
    public function toArray($xml){
        //禁止引用外部xml实体
        libxml_disable_entity_loader(true);
        $result= json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
        return $result;
    }
    //获取指定长度的随机字符串
    function getRandChar($length){
        $str = null;
        $strPol = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";
        $max = strlen($strPol)-1;

        for($i=0;$i<$length;$i++){
            $str.=$strPol[rand(0,$max)];//rand($min,$max)生成介于min和max两个数之间的一个随机整数
        }

        return $str;
    }

}